#!flask/bin/python
from flask import Flask, jsonify
from flask import abort, make_response, request 
import _thread
import sys,os,time

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'vehicleApp1',
        'description': u'Velocitas Applications.',
        'status': u'RUNNING',
        'done': False
    },
    {
        'id': 2,
        'title': u'databroker',
        'description': u'Kuksa.VAL.databroker',
        'status': u'RUNNING',
        'done': False
    },
    {
        'id': 3,
        'title': u's2s-services',
        'description': u'Kuksa.VAL.Service',
        'status': u'RUNNING',
        'done': False
    }

]

tasks = eval(open("cfg.dit").read())

def update_store_data():
    global tasks
    while 1:
        #print("data update proc")
        try:
            fn_writer = open("cfg.dit","w")
            fn_writer.write(str(tasks))
            fn_writer.close()
        except:
            pass
        time.sleep(2.0)

@app.route('/e2e/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

@app.route('/e2e/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    print(tasks)
    task = list(filter(lambda t: t['id'] == task_id, tasks))
    print('task:', dir(task))
    for ff in task:
        print(ff)
    if len(task) == 0:
        abort(404)
    return jsonify({'task': task[0]})


@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

@app.route('/e2e/api/v1.0/tasks', methods=['POST'])
def create_task():
    global tasks
    if not request.json or not 'title' in request.json:
        abort(400)
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False,
        'status':'Not deplyer'
    }
    tasks.append(task)
    return jsonify({'task': task}), 201

@app.route('/e2e/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    global tasks
    task = list(filter(lambda t: t['id'] == task_id, tasks))
    if len(task) == 0:
        abort(404)
    if not request.json:
        abort(400)
    if 'title' in request.json and type(request.json['title']) != unicode:
        abort(400)
    if 'description' in request.json and type(request.json['description']) is not unicode:
        abort(400)
    if 'done' in request.json and type(request.json['done']) is not bool:
        abort(400)
    task[0]['title'] = request.json.get('title', task[0]['title'])
    task[0]['description'] = request.json.get('description', task[0]['description'])
    task[0]['done'] = request.json.get('done', task[0]['done'])
    task[0]['status'] = request.json.get('status', task[0]['status'])
    print("request:", request)
    return jsonify({'task': task[0]})

@app.route('/e2e/api/v1.0/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    global tasks
    task = list(filter(lambda t: t['id'] == task_id, tasks))
    if len(task) == 0:
        abort(404)
    tasks.remove(task[0])
    return jsonify({'result': True})

_thread.start_new_thread(update_store_data, (()))
if __name__ == '__main__':
    app.run(port=6666,debug=True)
